import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import router from '@/router'
import layer from 'vue-layer'
import md5 from 'md5'
Vue.prototype.$layer = layer(Vue)

import {
	showLoading,
	hideLoading
} from './loading';

let isTest = 3
let $domain = '';
if(isTest==1){
	$domain = 'https://ceshi-furniture.jiaju01.com/'
}else if(isTest==2){
	$domain = 'https://tst.shengejiaju.cn/'
}else{
	$domain = 'https://master.shengejiaju.cn/'
}
Vue.prototype.$domain = $domain

axios.interceptors.request.use(config => {
	if(config.showLoading){
		showLoading(config.text)
	}
	return config
}, error => {
	return Promise.reject(error)
})

axios.interceptors.response.use(response => {
	hideLoading()
	return response.data
}, error => {
	hideLoading()
	return Promise.resolve(error.response)
})

function errorState(response) {
	Vue.prototype.$layer.msg('网络错误，请稍后重试!')
}

function successState(res) {
	if (res.code) {
		switch (Number(res.code)) {
			case 200:
				return res
				break;
			case 201:
				localStorage.removeItem('token')
				Vue.prototype.$layer.msg('登录失效，请重新登录')
				// return
				setTimeout(() => {
					router.push('/')
					// window.location.href = '/web/admin/'
				}, 1500)
				break;
			case 203:
				return res
				break;
			default:
				return Vue.prototype.$layer.msg(res.error)
				break;
		}
	} else {
		Vue.prototype.$layer.msg('网络错误，请稍后重试!')
	}
}

// 参数排序
function objKeySort(obj) {
	var newkey = Object.keys(obj).sort();
	var newObj = {};
	for (var i = 0; i < newkey.length; i++) {
		newObj[newkey[i]] = obj[newkey[i]];
	}
	return newObj;
}

const https = (opts, data) => {
	/* if(!localStorage.getItem('token')){
		Vue.prototype.$layer.msg('请先登录!')
		setTimeout(() => {
			window.location.href = '/'
		},1500)
		return
	} */

	if (!data) {
		data = {}
	}
	let isUpload;
	if (opts.url.indexOf('UpMajorImg') != -1 || opts.url.indexOf('UpViceImg') != -1 || opts.url.indexOf('UpInfoImg') != -
		1 || opts.url.indexOf('AddCaseImg') != -1 || opts.url.indexOf('Upimg/UpVideo') != -1 || opts.url.indexOf('UpImg') != -1 ||
		opts.url.indexOf('UpSkuImg') != -1 || opts.url.indexOf('AddImg') != -1 || opts.url.indexOf('/Admingzh/add_image') != -1
		|| opts.url.indexOf('UpTemplate') != -1) {
		
		isUpload = true
	} else {
		isUpload = false
	}
	if (isUpload) {
		data.append('timestamp', Math.round(new Date() * 1000))
		data.append('key', localStorage.getItem('token'))
		data.append('port', 'pc')
	} else {
		data.timestamp = Math.round(new Date() * 1000)
		if(localStorage.getItem('token')){
			data.key = localStorage.getItem('token')
		}
		data.port = 'pc'
		if (localStorage.getItem('filiale_id') != 1 && localStorage.getItem('filiale_id')) {
			data.filiale_id = localStorage.getItem('filiale_id')
		}
		if(data.is_filiale){
			delete data.filiale_id;
			delete data.is_filiale;
		}
	}

	if(data.sign){
		delete data.sign
	}

	// console.log(data)
	for(let i in data){
		if(data[i] == undefined || data[i]==='undefined'){
			data[i] = ''
		}
	}
	
	// 获取签名开始
	let obj = 'jjds2020+'
	let newObj = objKeySort(data)
	for (let i in newObj) {
		obj += i + '=' + newObj[i] + '&'
	}
	obj = obj.substring(0, obj.length - 1)
	obj += '+jjds2020'
	console.log(obj,'加密前')
	obj = md5(obj)
	obj = obj.toUpperCase()
	// 获取签名结束

	if (isUpload) {
		data.append('sign', obj)
	} else {
		data.sign = obj
	}

	let httpDefaultOpts = { //http默认配置
		method: opts.method,
		baseURL: $domain,
		url: opts.url,
		timeout: 20000,
		params: isUpload ? data : Object.assign(data),
		data: isUpload ? data : qs.stringify(Object.assign(data)),
		showLoading: opts.showLoading?opts.showLoading:false,
		text:opts.text?opts.text:'加载中...'
		// params: Object.assign(data),
		// data: qs.stringify(Object.assign(data))
	}
	if (opts.method == 'get') {
		delete httpDefaultOpts.data
	} else {
		delete httpDefaultOpts.params
	}
	let promise = new Promise(function(resolve, reject) {
		axios(httpDefaultOpts).then((res) => {
			if(res.status && res.status!=200){
				reject(res)
			}
			if (res.code == 200) {
				resolve(res)
			} else if(res.code==203){
				resolve(res)
			}else{
				successState(res)
			}
		}).catch((response) => {
			errorState(response)
			reject(response)
		})
	})
	return promise
}


// 日期格式转换
window.Date.prototype.Format = function(format) {
	var o = {
		//month
		"M+": this.getMonth() + 1,
		"d+": this.getDate(), //day
		"h+": this.getHours(), //hour
		"m+": this.getMinutes(), //minute
		"s+": this.getSeconds(), //second
		"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
		"S": this.getMilliseconds() //millisecond
	}
	if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
		(this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1,
				RegExp.$1.length == 1 ? o[k] :
				("00" + o[k]).substr(("" + o[k]).length));
	return format;
}

export default https
